import { ref } from 'vue'
import { supabase } from '../../lib/supabase'
import type { Comment, ReplyLoadParams, CacheItem } from './types'
import { useUiStore } from '../../store/useUiStore'

// 回复缓存系统
const replyCache = new Map<string, CacheItem<Comment[]>>()
const REPLY_CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

export const useCommentReplies = (commentId: number) => {
  const uiStore = useUiStore()
  const replies = ref<Comment[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const hasMore = ref(true)
  const currentPage = ref(0)
  const pageSize = ref(5)

  // 生成缓存键
  const getCacheKey = (commentId: number, page: number = 0) => {
    return `replies_${commentId}_${page}`
  }

  // 检查缓存是否有效
  const isCacheValid = (cacheKey: string) => {
    const cached = replyCache.get(cacheKey)
    if (!cached) return false
    return Date.now() - cached.timestamp < REPLY_CACHE_DURATION
  }

  // 从缓存获取数据
  const getFromCache = (cacheKey: string): Comment[] | null => {
    if (isCacheValid(cacheKey)) {
      return replyCache.get(cacheKey)!.data
    }
    return null
  }

  // 设置缓存
  const setCache = (cacheKey: string, data: Comment[]) => {
    replyCache.set(cacheKey, {
      data,
      timestamp: Date.now()
    })
  }

  // 批量获取用户信息（复用用户缓存）
  const batchGetUserProfiles = async (userIds: string[]) => {
    const userMap = new Map()
    
    if (userIds.length === 0) return userMap

    try {
      const { data: profilesData, error: profilesError } = await supabase
        .from('user_profiles')
        .select('id, user_id, name, avatar_url, is_ai')
        .in('user_id', userIds)
      
      if (!profilesError && profilesData) {
        profilesData.forEach(profile => {
          userMap.set(profile.user_id, profile)
        })
      }
    } catch (error) {
      console.error('Error fetching user profiles for replies:', error)
    }

    return userMap
  }

  // 加载回复（支持分页）
  const loadReplies = async (page: number = 0, append: boolean = false) => {
    const cacheKey = getCacheKey(commentId, page)
    
    // 检查缓存
    const cached = getFromCache(cacheKey)
    if (cached && !append) {
      replies.value = cached
      return
    }

    loading.value = true
    error.value = null
    
    try {
      const offset = page * pageSize.value
      
      // 获取回复数据（仅必要字段）
      const { data: repliesData, error: fetchError } = await supabase
        .from('comments')
        .select('id, user_id, content, likes, dislikes, created_at, updated_at')
        .eq('parent_id', commentId)
        .order('created_at', { ascending: true })
        .range(offset, offset + pageSize.value - 1)

      if (fetchError) {
        throw fetchError
      }

      // 获取所有用户ID
      const userIds = [...new Set(repliesData.map(reply => reply.user_id).filter(Boolean))]
      
      // 批量获取用户信息
      const userMap = await batchGetUserProfiles(userIds)

      // 过滤 AI 回复（基于用户 is_ai）
      const filteredRepliesData = uiStore.filterAiContent
        ? repliesData.filter((reply) => {
            const up = userMap.get(reply.user_id)
            return !up?.is_ai
          })
        : repliesData

      // 获取当前用户的投票状态（仅针对展示中的回复）
      const { data: { user } } = await supabase.auth.getUser()
      let userVotes = new Map()
      if (user) {
        const replyIds = filteredRepliesData.map(reply => reply.id)
        const { data: votes, error: votesError } = await supabase
          .from('comment_votes')
          .select('comment_id, vote_type')
          .eq('user_id', user.id)
          .in('comment_id', replyIds)

        if (!votesError && votes) {
          votes.forEach(vote => {
            userVotes.set(vote.comment_id, vote.vote_type)
          })
        }
      }

      // 转换数据格式
      const formattedReplies: Comment[] = filteredRepliesData.map((reply) => {
        const userProfile = userMap.get(reply.user_id)
        return {
          id: reply.id,
          userId: reply.user_id,
          user: {
            id: userProfile?.user_id || reply.user_id,
            name: userProfile?.name || '未知用户',
            avatar: userProfile?.avatar_url,
            isAi: userProfile?.is_ai || false
          },
          content: reply.content,
          likes: reply.likes,
          dislikes: reply.dislikes,
          replies: [], // 回复的回复暂时不加载
          createdAt: reply.created_at,
          updatedAt: reply.updated_at,
          userVote: userVotes.get(reply.id) || 0 // 添加用户投票状态
        }
      })

      // 更新状态
      if (append) {
        replies.value.push(...formattedReplies)
      } else {
        replies.value = formattedReplies
      }

      // 检查是否还有更多数据
      hasMore.value = formattedReplies.length === pageSize.value
      currentPage.value = page

      // 设置缓存
      setCache(cacheKey, formattedReplies)

    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载回复失败'
      console.error('加载回复失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 加载更多回复
  const loadMore = async () => {
    if (!hasMore.value || loading.value) return
    await loadReplies(currentPage.value + 1, true)
  }

  // 提交回复
  const submitReply = async (content: string, movieId?: number): Promise<boolean> => {
    try {
      // 获取当前用户
      const { data: { user }, error: userError } = await supabase.auth.getUser()
      if (userError || !user) {
        throw new Error('用户未登录')
      }

      // 如果没有提供movieId，需要从父评论中获取
      let targetMovieId = movieId
      if (!targetMovieId) {
        const { data: parentComment, error: parentError } = await supabase
          .from('comments')
          .select('movie_id')
          .eq('id', commentId)
          .single()
        
        if (parentError || !parentComment) {
          throw new Error('无法获取父评论信息')
        }
        targetMovieId = parentComment.movie_id
      }

      // 提交回复
      const { data, error } = await supabase
        .from('comments')
        .insert({
          parent_id: commentId,
          user_id: user.id,
          content: content,
          movie_id: targetMovieId
        })
        .select()
        .single()

      if (error) {
        throw new Error(`提交回复失败: ${error.message}`)
      }

      // 重新加载回复列表
      await loadReplies(0, false)

      return true
    } catch (err) {
      console.error('提交回复失败:', err)
      return false
    }
  }

  // 点赞回复
  const likeReply = async (replyId: number): Promise<{ success: boolean; action?: string; error?: string }> => {
    try {
      // 获取当前用户
      const { data: { user }, error: userError } = await supabase.auth.getUser()
      if (userError || !user) {
        throw new Error('用户未登录')
      }

      // 使用数据库函数处理点赞
      const { data, error } = await supabase
        .rpc('handle_comment_vote', {
          p_user_id: user.id,
          p_comment_id: replyId,
          p_vote_type: 1
        })

      if (error) {
        throw new Error(`点赞失败: ${error.message}`)
      }

      if (!data || !data.success) {
        throw new Error(data?.error || '点赞失败')
      }

      return { success: true, action: data.action }
    } catch (err) {
      console.error('点赞回复失败:', err)
      return { success: false, error: err instanceof Error ? err.message : '点赞失败' }
    }
  }

  // 点踩回复
  const dislikeReply = async (replyId: number): Promise<{ success: boolean; action?: string; error?: string }> => {
    try {
      // 获取当前用户
      const { data: { user }, error: userError } = await supabase.auth.getUser()
      if (userError || !user) {
        throw new Error('用户未登录')
      }

      // 使用数据库函数处理点踩
      const { data, error } = await supabase
        .rpc('handle_comment_vote', {
          p_user_id: user.id,
          p_comment_id: replyId,
          p_vote_type: -1
        })

      if (error) {
        throw new Error(`点踩失败: ${error.message}`)
      }

      if (!data || !data.success) {
        throw new Error(data?.error || '点踩失败')
      }

      return { success: true, action: data.action }
    } catch (err) {
      console.error('点踩回复失败:', err)
      return { success: false, error: err instanceof Error ? err.message : '点踩失败' }
    }
  }

  // 清除回复缓存
  const clearReplyCache = () => {
    replyCache.clear()
  }

  return {
    // 状态
    replies,
    loading,
    error,
    hasMore,
    currentPage,
    pageSize,
    
    // 方法
    loadReplies,
    loadMore,
    submitReply,
    likeReply,
    dislikeReply,
    clearReplyCache,
    
    // 缓存方法
    getCacheKey,
    isCacheValid,
    getFromCache,
    setCache,
    batchGetUserProfiles
  }
}
